const utils = require("./util");
const event = require("./event");

module.exports = () => {
	// 保存原始方法，因为我们不需要修改它的原始跳转逻辑
    const originNavigateTo = wx.navigateTo;
    const originRedirectTo = wx.redirectTo;
    const originSwitchTab = wx.switchTab;
    const originNavigateToMiniProgram = wx.navigateToMiniProgram;

    Object.defineProperty(wx, "navigateTo", {
        configurable: true, // 是否可以配置
        enumerable: true, // 是否可迭代
        writable: true, // 是否可重写
        value: function() {
            const config = arguments[0] || {}; // 获取
            const url = config.url;
            event.navToPage(url); // 上报跳转的url,此处是自己封装的方法，根据个人需要自定义
            return originNavigateTo.apply(this, arguments); // 原样移交函数参数和this
        }
    });

    Object.defineProperty(wx, "redirect", {
        configurable: true,
        enumerable: true,
        writable: true,
        value: function() {
            const config = arguments[0] || {};
            const url = config.url;
            event.navToPage(url);
            return originRedirectTo.apply(this, arguments);
        }
    });

    Object.defineProperty(wx, "switchTab", {
        configurable: true,
        enumerable: true,
        writable: true,
        value: function() {
            const config = arguments[0] || {};
            const url = config.url;
            event.navToPage(url);
            return originSwitchTab.apply(this, arguments);
        }
    });
    Object.defineProperty(wx, "navigateToMiniProgram", {
        configurable: true,
        enumerable: true,
        writable: true,
        value: function() {
            const config = arguments[0] || {};
            const originSuccess = config.success || function(){};
            const originFail = config.fail || function(){};
            config.success = function() {
                Object.assign(config, {
                    result: "success"
                });
                event.navToMp(config);
                originSuccess.apply(this, arguments);
            };
            config.fail = function(res) {
                Object.assign(config, {
                    result: "fail",
                    // errMsg:res.errMsg
                });
                event.navToMp(config);
                originFail.apply(this, arguments);
            };
            return originNavigateToMiniProgram.apply(this, arguments);
        }
    });
};

